package com.wqtz.chechai.view.activities;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.SaveCallback;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.orhanobut.logger.Logger;
import com.qiniu.android.http.ResponseInfo;
import com.wqtz.chechai.R;
import com.wqtz.chechai.adapter.PhotoAdapter;
import com.wqtz.chechai.base.BaseActivity;
import com.wqtz.chechai.bean.RefundReceiptData;
import com.wqtz.chechai.presenter.BasePresent;
import com.wqtz.chechai.utils.QiNiuUtils;
import com.wqtz.chechai.utils.SPUtils;
import com.wqtz.chechai.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 项目名称： CheChai
 * 创建人 :  Kisum
 * 创建时间: 2017/2/6
 * 上传退款回单图片页面
 */
public class UpLoadRefundReceiptPicActivity extends BaseActivity {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.btn_upload_pic)
    Button mBtnUploadPic;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    private PhotoAdapter photoAdapter;

    private ArrayList<String> qiNiuRefundReceiptPhotos = new ArrayList<>(); //放款回单照片七牛地址集合
    private SVProgressHUD svProgressHUD;
    private boolean renewIsOk = false;
    private AVQuery<AVObject> mAvQuery;
    private ArrayList<String> imagespath;
    private final int REQUEST_IMAGE = 2012;//获取退款图片
    private ArrayList<String> defaultDataArray;
    private RefundReceiptData mRefundReceiptData;

    @Override
    public void init() {
        ButterKnife.bind(this);
        mTvTitle.setText("上传退款回单");
        imagespath = new ArrayList<>();
        imagespath.add("default");//加号
        //归档图片本地地址集合存入对象
        mRefundReceiptData = new RefundReceiptData();
        mRefundReceiptData.setList(imagespath);
        photoAdapter = new PhotoAdapter(R.layout.item_image_selected, imagespath);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        //设置item间距
        int spacingInPixels = 8;
        mRecyclerView.addItemDecoration(new com.wqtz.chechai.widget.SpacesItemDecoration(spacingInPixels));
        mRecyclerView.setAdapter(photoAdapter);
        photoAdapter.setDelOnClickCallBack(new PhotoAdapter.delOnClickCallBack() {
            @Override
            public void onDelClick(int position) {
                if (position == 0) {
                    getPhoto();
                } else {
                    imagespath.remove(position);
                    photoAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void loadData() {

    }

    @Override
    public int setContentViews() {

            return R.layout.activity_upload_renew_info;
    }

    @Override
    public BasePresent createPresenter() {
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE: {
                    // Get the result list of select image paths
                    imagespath.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
                    SPUtils.put(this, "refundImages", imagespath);
                    ToastUtils.show(this, imagespath.get(0), 2000);
                    photoAdapter.notifyDataSetChanged();
                }
                break;
            }
        }
    }



    @OnClick({R.id.iv_back, R.id.btn_upload_pic})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_back:
                finish();
                break;
            //上传图片
            case R.id.btn_upload_pic:
                if (imagespath.size() == 1) {
                    ToastUtils.show(this, "您未选择任何图片", 2000);
                } else {
                    uploadImg();
                    //发布消息，将数据传给fragment
                    EventBus.getDefault().post(mRefundReceiptData);
                    this.finish();
                }
                break;
        }
    }

    public void getPhoto() {
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        defaultDataArray = new ArrayList<>();
        // whether show camera
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // max select image amount
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
        // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // default select images (support array list)
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    /**
     * 上传图片到七牛
     */
    private void uploadImg() {
        qiNiuRefundReceiptPhotos.clear();
        qiNiuRefundReceiptPhotos.addAll(makeUploadFileName("refundPic", imagespath));
        QiNiuUtils qiNiuUtils = new QiNiuUtils(imagespath, qiNiuRefundReceiptPhotos, new QiNiuUtils.isUploadSuccess() {
            @Override
            public void isUploadSusscess(String key, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    Logger.e("退款回单上传完毕" + info.toString());
                    renewIsOk = true;
                    if (renewIsOk) {
                        String path = info.toString();
                        Logger.e("返回的下载地址:" + path);
                        upDataToLeanCloud();
                        ToastUtils.showShort(UpLoadRefundReceiptPicActivity.this,"上传成功");
                    }
                }
            }

            @Override
            public void upLoadProgress(String key, double progress) {
                Logger.e(progress * 100 + key + "退款回单");
            }
        });
    }

    /**
     * 保存图片url到leancloud
     */
    private void upDataToLeanCloud() {
        AVObject product = new AVObject("RefundReceiptPhotoGroup");
        product.put("qiNiuRefundReceiptPhotos", "7y8l76.com1.z1.glb.clouddn.com/" + qiNiuRefundReceiptPhotos.get(0));
        product.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    svProgressHUD = new SVProgressHUD(UpLoadRefundReceiptPicActivity.this);
                    svProgressHUD.showSuccessWithStatus("提交完成");
                    finish();
                } else {
                    svProgressHUD.showSuccessWithStatus("提交失败");
                }
            }
        });

    }

    private ArrayList<String> makeUploadFileName(String renewPic, List<String> localpath) {
        //文件名构造
        ArrayList<String> finelists = new ArrayList<>();
        if (localpath.size() == 0) {
            return null;
        }
        for (int i = 0; i < localpath.size(); i++) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(renewPic).
                    append(localpath.get(i));//取本地图库文件名为七牛存储文件名
            finelists.add(stringBuffer.toString());
        }

        return finelists;
    }

}
